import * as request from 'supertest';
import 'mocha';
import app from '../app';
import config from '../config';
import { signSync } from '../plugin/jwt';
import * as process from 'process';
import User from '../model/User';
import { md5WithSecret } from '../utils';

const user1 = {
  account: 'root'
};
const user2 = {
  account: 'admin',
  password: 'admin',
};
const password = 'root';

const getAuthorization = (jwt: string) => `Bearer ${jwt}`;
const userAuth = getAuthorization(signSync(user1));

describe('# API接口测试', () => {
  const server = app.listen(config.port);
  before(async () => {
    // 防止悲剧发生
    if (process.env['NODE_PROD'] === '1') throw new Error('线上环境不允许运行测试!!!');
    await User.truncate();
    await User.create(Object.assign({}, user1, { password: md5WithSecret(password) }));
  });

  describe('# 越权测试', async () => {
    it('# GET /api/users 未登录', async () => {
      return request(server)
        .get('/api/users')
        .expect(400);
    });
  });

  describe('# user', async () => {
    it('# GET /api/users', async () => {
      return request(server)
        .get('/api/users')
        .set('Authorization', userAuth)
        .expect(200);
    });

    it('# GET /api/token', async () => {
      return request(server)
        .get(`/api/token?account=${user1.account}&password=${password}`)
        .expect(200);
    });

    it('# GET /api/token 账号错误', async () => {
      return request(server)
        .get(`/api/token?account=hhhhh&password=${password}`)
        .expect(400);
    });

    it('# GET /api/token 密码错误', async () => {
      return request(server)
        .get(`/api/token?account=${user1.account}&password=hhhhh`)
        .expect(400);
    });

    it('# GET /api/user/:id', async () => {
      return request(server)
        .get('/api/user/1')
        .set('Authorization', userAuth)
        .expect(200);
    });

    it('# POST /api/user', async () => {
      return request(server)
        .post('/api/user')
        .send(user2)
        .expect(200);
    });

    it('# UPDATE /api/user/:id', async () => {
      return request(server)
        .put('/api/user/1')
        .send({ password: '1234' })
        .set('Authorization', userAuth)
        .expect(200);
    });

    it('# DELETE /api/user/:id', async () => {
      return request(server)
        .del('/api/user/1')
        .set('Authorization', userAuth)
        .expect(200);
    });
  });

});
